'use strict';

/**
 * Created by zhu on 14/12/26.
 */
angular.module('blog').controller('BlogDetailCtrl', [
    '$scope',
    '$cookies',
    '$rootScope',
    '$sce',
    '$location',
    '$routeParams',
    'PathSuffixConstant',
    'BlogDetailService',
    'BlogRecycleManageService',
    function ($scope, $cookies, $rootScope, $sce, $location, $routeParams, PathSuffixConstant, BlogDetailService, BlogRecycleManageService) {
        var blogId = $routeParams.blogId;

        $rootScope.visitedUserId = $routeParams.userId;

        if (!$rootScope.newBlog) {
            BlogDetailService.query({blogId: blogId + PathSuffixConstant}, function (response) {
                $scope.blog = response;
            }, function(response) {
                if (response.status == 404) {
                    $location.path("404");
                }
            });
        } else {
            $scope.blog = initializeNewBlog($rootScope.newBlog);
            $rootScope.newBlog = null;
            //$scope.$broadcast('BlogCreatedEvent', $scope.blog.categoryId._id);
        }

        $scope.remove = function (blog) {
            if (confirm('是否删除\"' + blog.name + '\"?')) {
                BlogRecycleManageService.add({identity: blogId}, function () {
                    $location.path(blogId + '/blog');
                    $rootScope.deletedBlogId = blogId;
                });
            }
        };

        $scope.safeHtml = function (blog) {
            if (blog) {
                return $sce.trustAsHtml(blog.content);
            }
        };

        function initializeNewBlog(blog) {
            blog.replies = 0;
            blog.views = 0;
            blog.createTime = {$date: new Date()};
            blog.author = {
                id: $cookies.userid,
                name: $cookies.username
            };
            blog._id = blogId;
            return blog;
        }

    }]);
